﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace elibrary.Classes.Filters
{
    public class AccessControlFilter : ActionFilterAttribute
    {
        public bool mustAuthenticate { get; set; }
        public bool forAdmin { get; set; }

        public AccessControlFilter()
        {
            mustAuthenticate = true;
            forAdmin = false;
        }

        /// <summary>
        /// Provides Access Control to Pages
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpSessionStateBase Session = filterContext.HttpContext.Session;
            bool isAuthenticated = Session["isAuthenticated"] != null && ((bool)(Session["isAuthenticated"]));
            bool isAdmin = isAuthenticated && Session["isAdmin"] != null && ((bool)(Session["isAdmin"]));

            if (mustAuthenticate && !isAuthenticated)
            {
                Session["errorMsg"] = "You must login to view the page.";
                filterContext.HttpContext.Server.Transfer("/login");
                return;
            }

            if (forAdmin && !isAdmin)
            {
                Session["errorMsg"] = @"You are not authorized to access this page. Please contact the administrator
                                      if you think this is a mistake. Otherwise try logining again. Thank you.";
                filterContext.HttpContext.Server.Transfer("/login");
                return;
            }

            base.OnActionExecuting(filterContext);
        }
    }
}